package com.kemai.customize

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.kemai.view.R

/**

 *@description:TODO
 * @author: zhaoshanshan
 * @date: 2022/11/17 10:55 下午

 */
 class ColorTraceTextView: AppCompatTextView {

    private lateinit var direction:Direction;
    private var originPaint:Paint? = null
    private var changePaint:Paint? = null
    private var currentPosition = 0.0f

    enum class Direction {
        LEFT_TO_RIGHT,RIGHT_TO_LEFT
    }

    constructor(context:Context):this(context,null){


    }
    constructor(context:Context, attrs: AttributeSet?) :this(context,attrs,0){

    }
    constructor(context:Context, attrs: AttributeSet?, defStyleAttr:Int) :super(context,attrs,defStyleAttr){

        initPaint(context,attrs)
    }

    private fun initPaint(context:Context,attrs:AttributeSet?){

        val typedArray =  context.obtainStyledAttributes(attrs,R.styleable.ColorTrackTextView)
        val originColor = typedArray.getColor(R.styleable.ColorTrackTextView_originColor,textColors.defaultColor)
        val changeColor = typedArray.getColor(R.styleable.ColorTrackTextView_changeColor,textColors.defaultColor)
        originPaint =getPaintByColor(originColor)
        changePaint =getPaintByColor(changeColor)
        typedArray.recycle()//回收

    }
    private fun getPaintByColor(color:Int): Paint {

        val paint = Paint()
        paint.color = color
        paint.isAntiAlias = true//防锯齿
        paint.isDither = true//防抖动
        paint.textSize = textSize
        return paint

    }

    override fun onDraw(canvas: Canvas?) {
        val currentPoint = (currentPosition*width).toInt()
        if(direction==Direction.LEFT_TO_RIGHT){//从左到右
           drawText(canvas,changePaint!!,0,currentPoint)
           drawText(canvas,originPaint!!,currentPoint,width)

        }
        else{
           drawText(canvas,changePaint!!,width-currentPoint,width)
           drawText(canvas,originPaint!!,0,width-currentPoint)

        }
    }

    private fun drawText(canvas: Canvas?,paint:Paint,start:Int,end:Int){

        if(text.isEmpty()) return
        canvas?.save()
        val rect = Rect(start,0,end,height)
        canvas?.clipRect(rect)
        var bounds = Rect()
        paint?.getTextBounds(text.toString(),0,text.length,bounds)
        val dx = (width/2)-(bounds.width()/2)
        val fontMetricsInt = paint!!.fontMetricsInt
        val dy = (fontMetricsInt?.bottom!! -fontMetricsInt?.top)/2-fontMetricsInt?.bottom
        val baseLine = (height/2)+dy;
        canvas?.drawText(text.toString(), dx.toFloat(), baseLine.toFloat(),paint!!)
        canvas?.restore()

    }

    fun setDirection(directionValue:Direction){
        direction = directionValue
    }
     fun setCurrentPoint(currentPoint:Float){
        currentPosition = currentPoint
        invalidate()
    }


}